package stream.ThreadSafe;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.StampedLock;

/**
 * Created on 2018/12/17.
 */
public class StampedSample {
    private final StampedLock sl = new StampedLock();
    private final Map<String, String> m = new TreeMap<>();

    void mutate() {
        long stamp = sl.writeLock();
        try {
//            write();
            m.put("key", "value");
        } finally {
            sl.unlockWrite(stamp);
        }
    }

    String access() {
        long stamp = sl.tryOptimisticRead();
//        String data = read();
        String data = m.get("key");
        if (!sl.validate(stamp)) {
            stamp = sl.readLock();
            try {
                data = m.get("key");
            } finally {
                sl.unlockRead(stamp);
            }
        }
        return data;
    }
    // …
}

